package org.example.algorithm.dp;

public class LongestCommonSubsequenceSolution {

    public int longestCommonSubsequence(String text1, String text2) {
        int max = 0;
        int[][] dp = new int[text1.length()][text2.length()];
        for (int i=0;i<text1.length();i++) {
            for (int j=0;j<text2.length();j++) {
                if (text1.charAt(i) == text2.charAt(j)) {
                    if (i>=1 && j>=1) {
                        dp[i][j] = dp[i-1][j-1] + 1;
                    } else {
                        dp[i][j] = 1;
                    }
                } else {
                    if (i>=1 && j>=1) {
                        dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                    } else if(i>=1) {
                        dp[i][j] = dp[i-1][j];
                    } else if(j>=1) {
                        dp[i][j] = dp[i][j-1];
                    } else {
                        dp[i][j] = 0;
                    }
                }
                max = Math.max(max, dp[i][j]);
            }
        }
        return max;
    }

    public static void main(String[] args) {
        String text1 = "abcde";
        String text2 = "ace";
        LongestCommonSubsequenceSolution solution = new LongestCommonSubsequenceSolution();
        int res = solution.longestCommonSubsequence(text1, text2);
        System.out.println(res);
    }
}
